let body,httpInfo,httpMethod,headers;
const { result } = require("common-utils");
const uniID=require("uni-id-common");
const db = uniCloud.database();
const dbCmd = db.command;
module.exports = {
	_before: function () { // 通用预处理器
		httpInfo = this.getHttpInfo();
		if(httpInfo.httpMethod!='POST') throw result({code:400,msg:"error"})
		body = httpInfo.body ? JSON.parse(httpInfo.body) : '';	
		({headers=null} = httpInfo);
	},
	//登录接口
	async login(){		
		let {username=null,password=null} = body;		
		if(!username) return result({code:400,msg:"required",custom:"用户名必填"});
		if(!password) return result({code:400,msg:"required",custom:"密码必填"});
		const {data:{errCode=null,errMsg=null,newToken=null}} = await uniCloud.httpclient.request("https://fc-mp-54078533-0cb4-46b0-aa85-4d88df83247f.next.bspapp.com/uni-id-co/login", {
			method: 'POST',
			dataType: 'json',
			headers: {
				'Content-Type': 'application/json'
			},
			data:{
				clientInfo:{
					uniPlatform:"web",
					appId:"__UNI__90184A1",
					deviceId:"17127172375149877743"
				},
				params: {
					username,
					password
				}
			}
		});
		
		if(!newToken) return result({code:400,msg:"noSuccess",custom:errMsg});		
		return result({code:200,msg:"success",data:newToken})
		
	},
	//退出登录接口
	async logout(){		
		if(!headers.token) return result({code:400,msg:"required",custom:"未正确传递token"})
		const clientInfo = this.getClientInfo()
		const uniIDIns = uniID.createInstance({
			clientInfo
		})	
		let {errCode,uid,exp} =  await uniIDIns.checkToken(headers.token);
		if(errCode == 'uni-id-check-token-failed') return result({code:403,msg:"error",custom:"token校验未通过"});
		if(errCode == 'uni-id-token-expired') return result({code:401,msg:"error",custom:"token已失效"});
		await db.collection("uni-id-users").doc(uid).update({
			token:dbCmd.pull(headers.token)
		})
		return result({code:200,msg:"success"});		
		
	}
}
